<template>
  <label class="btn-file">
    <input type="file" :name="name" :multiple="multiple">
    <slot></slot>
  </label>
</template>
<script>
import {dotData, alert} from '@/utils'
import {getToken} from '@/utils/ajax'
import {urlPrefix} from '@/config/index.js'

export default {
  name: 'BaseUpload',
  props: {
    url: {
      type: String,
      required: true
    },
    multiple: {
      type: Boolean,
      default: true
    },
    name: {
      type: String,
      default: 'file'
    },
    formData: {
      type: Object,
      required: true
    },
    acceptFileTypes: {
      type: RegExp,
      default: undefined
    },
    autoUpload: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      fileList: []
    }
  },
  mounted() {
    let id = 1
    const ele = this.$el.querySelector('input[type="file"]')
    const token = getToken()
    window.$(ele).fileupload({
      formData: this.formData,
      acceptFileTypes: this.acceptFileTypes,
      url: urlPrefix + this.url,
      headers: {token: token},
      dropZone: ele,
      dataType: 'json',
      autoUpload: this.autoUpload,
      fail: () => {
        alert('文件上传失败')
      },
      processstart: (e) => {
      },
      processdone: (e, data) => {
        data.indexId = id
        this.fileList.push(data)
        this.$emit('file', data)
        this.$emit('files', this.fileList)
        id++
      },
      processfail: (e, data) => {
        const file = dotData(data, 'files[0]')
        alert('验证失败：' + file.error)
      }
    })
  },
  methods: {
    upload(file) {
      file.submit()
    }
  }
}
</script>
